//////////////////////////////////////////////////////////////////////////////////
// Who  : Lim, Dong-moon (dmlim@nate.com, 011-701-9381)
// When : 2005/11/29
//////////////////////////////////////////////////////////////////////////////////

#ifndef __NCRYPT_UTIL_H__
#define __NCRYPT_UTIL_H__

#ifdef WIN32

#include <windows.h>

#ifdef _WIN32_WCE
#include <wincrypt.h>
#else
#include <crtdbg.h>
#endif // _WIN32_WCE

#include <tchar.h>

#else

#include <ncrypt_types.h>

#endif // WIN32

#include <stdio.h>
#include <string>
#include <nblob.h>

using namespace std;

struct INT_STR
{
	DWORD dwCode;
	LPCTSTR szMessage;
};

bool is_white_space(char x);
void trim_string(string& x);
BOOL MyReadFile(LPCTSTR lpszFileName, BYTE** ppbData, DWORD* pdwDataLen);
BOOL MyWriteFile(LPCTSTR lpszFileName, BYTE* pbData, DWORD dwDataLen);
BOOL MyWriteFile(LPCTSTR, NBLOB*);
void ReverseBytes(BYTE* pBytes, UINT size);
void PrintBytes(BYTE* pBytes, UINT size, UINT bpl);

#define SET_ERROR_MESSAGE(msg) SetErrorMessage((msg), __LINE__, TEXT(__FILE__))

typedef void (__cdecl *ERROR_HANDLER_FN )(LPCTSTR, int, LPCTSTR);
typedef void(__cdecl *KeyValueParserCallback)(
	char* key_start, char* key_end, 
	char* val_start, char* val_end, void* param);

void SetErrorHandler(ERROR_HANDLER_FN);
void SetErrorMessage(LPCTSTR msg, int line, LPCTSTR file);
void NCryptHandleError(LPCTSTR s, BOOL bExit = TRUE, LPCTSTR lpszFileName = NULL, UINT line = 0);
LPCTSTR GetAlgNameFromID(ALG_ID id);
ALG_ID GetAlgIDFromName(LPCTSTR szAlgName);
LPCTSTR GetCryptoErrorMessage(DWORD dwErrorCode);
WCHAR* UTF8toUTF16(const char*);
char* UTF16toUTF8(const WCHAR*);
WCHAR* ANSItoUTF16(const char*, const char* charset = 0);
char* UTF16toANSI(const WCHAR*, const char* charset = 0);
void KeyValueParserUtil(char* org, char rec_delim, char key_delim, KeyValueParserCallback cb, void* param);
BOOL ReadPEMCertificate(LPCTSTR lpszFileName, BYTE** ppbData, DWORD* pcbData);
BOOL ReadPEMCertificates(LPCTSTR lpszFileName, int* pBlobsLen, NBLOB* pBlobs);

#ifdef WIN32
int PathUnixToWin(const TCHAR* src, TCHAR* dst);
#define _NPATH(v,x) TCHAR v[MAX_PATH]; int _NPATH_DUMMY_##v = PathUnixToWin(_T(x), v);
#else
#define _NPATH(v,x) LPCTSTR v = _T(x);
#endif

#endif // __NCRYPT_UTIL_H__

extern ERROR_HANDLER_FN gSetErrorMessage;
